package com.fare.fdc.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.application.AnalyseQueryApplication;
import com.fare.taluo.application.LowestPriceQueryApplication;
import com.fare.taluo.application.analyse.ChannelContrastApplication;
import com.fare.taluo.application.analyse.PriceSearchApplication;
import com.fare.taluo.application.fetl.DoublePlaneInfoApplication;
import com.fare.taluo.application.fetl.SinglePlaneInfoApplication;
import com.fare.taluo.application.fetl.history.IDoublePlaneInfoHistoryApplication;
import com.fare.taluo.application.fetl.history.ISinglePlaneInfoHistoryApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.plane.city.CityQueryApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.plane.flight.FlightInfoApplication;
import com.fare.taluo.application.plane.income.FreightPublishApplication;
import com.fare.taluo.auth.security.ContextLoginUser;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.util.I18nUtil;
import com.fare.taluo.util.JsonUtil;
import com.fare.taluo.vo.core.FreightPublishVO;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.core.QueryVo;
import com.fare.taluo.vo.core.SourceEntityVO;

/**
 * 运价查询
 * @author spring.华 
 */
@Controller("lowestPriceQueryAction")
@Scope("prototype")
public class LowestPriceQueryAction extends BaseFdcAction{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6983680389578813188L;

	public Logger logger = LoggerFactory.getLogger(LowestPriceQueryAction.class);
	
	@Resource(name="analyseQueryApplication")
	private AnalyseQueryApplication analyseQueryApplication;   //原AnalyseQueryApplication
	@Resource(name="lowestPriceQueryApplication")
	private LowestPriceQueryApplication lowestPriceQueryApplication;
	@Resource(name="portApplication")
	private PortApplication portApplication;
	@Resource(name="priceSearchApplication")
	private PriceSearchApplication priceSearchApplication;
	@Resource(name="channelContrastApplication")
	private ChannelContrastApplication channelService;
	/**
	 *  实时单程
	 */
	@Inject
	private SinglePlaneInfoApplication singlePlaneInfoApplication;
	/**
	 * 实时往返
	 */
	@Inject
	private DoublePlaneInfoApplication doublePlaneInfoApplication;
	
	/**
	 *  历史单程
	 */
	@Inject
	private ISinglePlaneInfoHistoryApplication singlePlaneInfoHistoryApplication;
	/**
	 * 历史往返
	 */
	@Inject
	private IDoublePlaneInfoHistoryApplication doublePlaneInfoHistoryApplication;
	
	private String fromCityCode;
	private String toCityCode;
	private String channelKey;
	
	private String language;
	
	private String inputDeptCitys;
	private String inputArrCityCodes;
	
	@Resource(name="sourceApplication")
	private SourceApplication sourceApplication;
	private QueryVo  vo;
	private   List<SourceEntityVO>  sourceLists;
	private  List<SourceEntityVO> channelsList;

	@Resource(name="flightInfoApplication")
	private FlightInfoApplication flightInfoApplication;
    @Resource(name="freightPublishApplication")
    private FreightPublishApplication freightPublishApplication ;
    @Resource(name="cityQueryApplication")
    private CityQueryApplication cityQueryApplication ;
    private FreightPublishVO freightPublishVO; 

	/**
	 * 进入查询运价页面
	 * @return
	 * @throws Exception
	 */
	public String toAnalyseJSP() throws Exception{
		sourceLists=sourceApplication.findCrawlAirCompanys();
		channelsList=sourceApplication.findCrawlChannel();
		Locale locale = super.getLocale();
		I18nUtil.sourceConvert2I18N(sourceLists, locale);
		I18nUtil.sourceConvert2I18N(channelsList, locale);
		vo = new QueryVo();
		vo.setCarrier(ContextLoginUser.getLoginUser().getSourceKey());
		returnPageURL = "/fare/_zuidijiachaxun.jsp";
		language=locale.toString();
		if(!language.equalsIgnoreCase("zh_CN") && !language.equalsIgnoreCase("en_US")){
			language="other";
		}
		return "dispatcher";
	}
	/**
	 * 点击查询按钮后的查询方法
	 */
	public void analyse(){
		List<PlaneInfo> results = null;
		try{
			if((fromCityCode ==null || "".equals(fromCityCode))&& inputDeptCitys !=null && !"".equals(inputDeptCitys) ){
				fromCityCode=inputDeptCitys.substring(inputDeptCitys.indexOf("(")+1, inputDeptCitys.lastIndexOf(")"));
			}
			if((toCityCode ==null || "".equals(toCityCode))&& inputArrCityCodes !=null && !"".equals(inputArrCityCodes)){
				toCityCode=inputArrCityCodes.substring(inputArrCityCodes.indexOf("(")+1, inputArrCityCodes.lastIndexOf(")"));
			}
			//获得航线的标准运价
			 freightPublishVO = freightPublishApplication.findByLine(fromCityCode, toCityCode);
			 if("doubleTrip".equals(vo.getQueryType())){//往返程数据
				 if(vo.getGrapDate().equals(DateUtils.getDateStr("yyyy-MM-dd"))){//实时数据
					 results = doublePlaneInfoApplication
							 .queryFreightPrice(channelKey, vo.getCarrierKey(),
									 fromCityCode, toCityCode, 
									 vo.getDepTime(), vo.getReturnDate());
				 }else{//历史数据
					 results = doublePlaneInfoHistoryApplication.queryFreightPrice(
							 DateUtils.strToDate(vo.getGrapDate(),
							 "yyyy-MM-dd"), 
							 channelKey, vo.getCarrierKey(), fromCityCode, toCityCode, 
							 DateUtils.strToDate(vo.getDepTime(),"yyyy-MM-dd"),
							 DateUtils.strToDate(vo.getReturnDate(),"yyyy-MM-dd"));
							
				 }
			 }else{ //单程数据
				 if(vo.getGrapDate().equals(DateUtils.getDateStr("yyyy-MM-dd"))){//实时数据
					 results = singlePlaneInfoApplication
						 .queryFreightPrice(channelKey, vo.getCarrierKey(),
								 fromCityCode, toCityCode, vo.getDepTime());
				 }else{
					 results =  singlePlaneInfoHistoryApplication.queryFreightPrice(
							 DateUtils.strToDate(vo.getGrapDate(),
							 "yyyy-MM-dd"), 
							 channelKey, vo.getCarrierKey(), fromCityCode, toCityCode, 
							 DateUtils.strToDate(vo.getDepTime(),"yyyy-MM-dd"));
				 }
			 }
			 //按选择的时间过滤结果列表
			 //如果没有勾选时间，则不需要过滤
			 List<Integer> notimes = this.getNoTimes(vo.getCheckbox());
			 if(!notimes.isEmpty()){ //没有全部勾选时间
				 results = this.filterNoTimesData(notimes, results);
			 }
			 Locale locale = super.getLocale();
			 I18nUtil.planeInfoConvert2I18N(results, locale);
			 //标准运价
			 String stardardPrice = freightPublishVO==null ? "1" : String.valueOf(freightPublishVO.getStandardPrice());
			 //组装结果数据
			 Collections.sort(results, new Comparator<PlaneInfo>(){
				@Override
				public int compare(PlaneInfo o1, PlaneInfo o2) {
//					return o1.getLowerPrice().compareTo(o2.getLowerPrice())!=0?
//							o1.getLowerPrice().compareTo(o2.getLowerPrice()):
//							o1.getFlightStartHour()-o2.getFlightStartHour();
					return o1.getFlightStartHour()-o2.getFlightStartHour();//按出发时间排序
				}
			 });
			 
			 String jsonStr = JsonUtil.toJson(results);
			 String data = "{\"jsonSize\":"+results.size()+
					 ","+"\"jsonString\":"+jsonStr+","+"\"standardPrice\":"+stardardPrice+"}";
			 super.toJSONOut(data);

		} catch (Exception e) {
			e.printStackTrace();
			super.toJSONOut("{\"status\": 0}");
		}
	}
	/**
	 * 获得不需要查询的时间,小时
	 * <p>
	 * M早上区间是：8-12
	 * B中午区间是：12-14
	 * A下午区间是：14-18
	 * N晚上区间是：18-24
	 * @param time 已选择的时间区间
	 * @return
	 */
	private List<Integer> getNoTimes(String time){
		List<Integer> list  = new ArrayList<Integer>();
		if(time.indexOf("M")<0){ //小于0则没有勾选
			list.add(8);
			list.add(9);
			list.add(10);
			list.add(11);
		} 
		if(time.indexOf("B")<0){
			list.add(12);
			list.add(13);
		} 
		if(time.indexOf("A")<0){
			list.add(14);
			list.add(15);
			list.add(16);
			list.add(17);
		} 
		if(time.indexOf("N")<0){
			list.add(18);
			list.add(19);
			list.add(20);
			list.add(21);
			list.add(22);
			list.add(23);
			list.add(00);
			list.add(01);
			list.add(02);
			list.add(03);
			list.add(04);
			list.add(05);
			list.add(06);
			list.add(07);
		}
		return list;
	}
	
	private List<PlaneInfo> filterNoTimesData(List<Integer> notimes, List<PlaneInfo> results){
		List<PlaneInfo> newInfos = new ArrayList<PlaneInfo>();
		for (PlaneInfo p : results) {   
			if(!notimes.contains(p.getFlightStartHour())){
				newInfos.add(p); //符合时间的才加入到列表上
			}
		}
		return newInfos;
	}
	
	public String getFromCityCode() {
		return fromCityCode;
	}
	public void setFromCityCode(String fromCityCode) {
		this.fromCityCode = fromCityCode;
	}
	public String getToCityCode() {
		return toCityCode;
	}
	public void setToCityCode(String toCityCode) {
		this.toCityCode = toCityCode;
	}
	public List<SourceEntityVO> getSourceLists() {
		return sourceLists;
	}
	public void setSourceLists(List<SourceEntityVO> sourceLists) {
		this.sourceLists = sourceLists;
	}
	public List<SourceEntityVO> getChannelsList() {
		return channelsList;
	}
	public void setChannelsList(List<SourceEntityVO> channelsList) {
		this.channelsList = channelsList;
	}
	public void setVo(QueryVo vo) {
		this.vo = vo;
	}
	public QueryVo getVo() {
		return vo;
	}
	public String getChannelKey() {
		return channelKey;
	}
	public void setChannelKey(String channelKey) {
		this.channelKey = channelKey;
	}
	public String getLanguage() {
		return language;
	}
	public void setLanguage(String language) {
		this.language = language;
	}
	public String getInputDeptCitys() {
		return inputDeptCitys;
	}
	public void setInputDeptCitys(String inputDeptCitys) {
		this.inputDeptCitys = inputDeptCitys;
	}
	
	
}
